const DB = require('./DB.js');
const Utils = require('lsd-utils');
const db = new DB();
class BaseDB {
    constructor(opt) {

    }
    _getData() {
        let data = {};
        console.log(this)
        for (let i in this) {
            console.log(i)
            let field = i.split('$$');
            if (field[1]) {
                data[field[1]] = this[i];
            }
            // data.i=i;
        }
        // console.log(field);
        return data;
    }
    insert(data) {
        console.log('insert')
        data = data || this._getData();
        let value = [];
        for (let i in data) {
            if(!!data[i]){
                value.push(`'${data[i]}'`)
            }else{
                if(this.COLUMN_KEY==i){
                    value.push(`'0'`)
                }else{
                    value.push(`''`)
                }
            }
            
        }
<<<<<<< HEAD
        db.sql(`INSERT INTO ${this.TABLE_NAME} 
                 VALUES(${value.join(',')})`)
=======
        db.query(`INSERT INTO ${this.TABLE_NAME} VALUES(`)
            .appendSQL(value.join(','))
            .appendSQL(')')
>>>>>>> 37ac7164ca0a9d34ef488540a2fdaf2c561db1ee
            .end();
        db.close();
    }
    save(data) {
        // INSERT INTO 表名称 VALUES (值1, 值2,....)
        data = data || this._getData();
        // console.log(data)
        // console.log(data[this.COLUMN_KEY])
        if (Utils.isNull(data[this.COLUMN_KEY])) {
            this.update(data);
        } else {
            this.insert(data);
        }
        console.log('*********data')
        console.log(data)
    }
    update(data) {
        console.log('update')
            //UPDATE table_name SET field1=new-value1, field2=new-value2
        data = data || this._getData();
        let value = [];
        for (let i in data) {
            value.push(`${i}='${data[i]}'`)
        }
<<<<<<< HEAD
        db.query(`UPDATE ${this.TABLE_NAME} SET 
                  ${value.join(',')}`)
=======
        db.query(`UPDATE ${this.TABLE_NAME} SET `)
            .appendSQL(`${value.join(', ')}`)
>>>>>>> 37ac7164ca0a9d34ef488540a2fdaf2c561db1ee
            .where(`${this.COLUMN_KEY} = ${data[this.COLUMN_KEY]}`)
            .end()
        console.log(db.sql)
    }
    query(){
<<<<<<< HEAD
        db.query(`select * from  ${this.TABLE_NAME} `);
        let data = this._getData();
        for(let item in data){
            if(!!data[item]){
               db.where(` ${item}= ${data[item]} `)
            }
            
=======
        db.query(`select * from  ${this.TABLE_NAME}  `)
        let data = this._getData();
        for(let i in data){
            if(!!data[i]){
                db.where(`${i} = ${data[i]}`)
            }          
>>>>>>> 37ac7164ca0a9d34ef488540a2fdaf2c561db1ee
        }
        return db.end();
    }
    find() {}
}
module.exports = BaseDB